<script setup>
import { ref, onMounted, nextTick } from 'vue'

const messages = ref([])
const inputMessage = ref('')
const chatContainer = ref(null)
const isLoading = ref(false)

// 从 localStorage 加载历史消息
onMounted(() => {
  const savedMessages = localStorage.getItem('chat-history')
  if (savedMessages) {
    messages.value = JSON.parse(savedMessages)
  }
})

// 保存消息到 localStorage
const saveMessages = () => {
  localStorage.setItem('chat-history', JSON.stringify(messages.value))
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: inputMessage.value,
    timestamp: new Date().toLocaleTimeString()
  })

  const userMessage = inputMessage.value
  inputMessage.value = ''
  isLoading.value = true

  try {
    // 这里替换为实际的 API 调用
    const response = await fetch('YOUR_API_ENDPOINT', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: userMessage
      })
    })

    const data = await response.json()
    
    // 添加 AI 响应
    messages.value.push({
      role: 'assistant',
      content: data.response, // 根据实际 API 响应调整
      timestamp: new Date().toLocaleTimeString()
    })
  } catch (error) {
    console.error('Error:', error)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，发生了一些错误，请稍后再试。',
      timestamp: new Date().toLocaleTimeString()
    })
  } finally {
    isLoading.value = false
    saveMessages()
    scrollToBottom()
  }
}

// 清空对话历史
const clearHistory = () => {
  messages.value = []
  saveMessages()
}
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>AI 助手</h2>
      <button @click="clearHistory" class="clear-button">
        清空对话
      </button>
    </div>

    <div class="messages" ref="chatContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message', message.role]"
      >
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ message.timestamp }}</div>
        </div>
      </div>
      <div v-if="isLoading" class="message assistant">
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="input-container">
      <textarea
        v-model="inputMessage"
        @keyup.enter.exact="sendMessage"
        placeholder="输入消息，按 Enter 发送..."
        rows="3"
      ></textarea>
      <button 
        @click="sendMessage"
        :disabled="isLoading || !inputMessage.trim()"
      >
        发送
      </button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  max-width: 1200px;
  margin: 0 auto;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.clear-button {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-button:hover {
  background-color: #e0e0e0;
}

.messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  margin-bottom: 10px;
}

.message.user {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.user .message-content {
  background-color: #007AFF;
  color: white;
  border-radius: 12px 12px 0 12px;
}

.assistant .message-content {
  background-color: #f0f0f0;
  color: #333;
  border-radius: 12px 12px 12px 0;
}

.message-time {
  font-size: 12px;
  margin-top: 4px;
  opacity: 0.7;
}

.input-container {
  display: flex;
  gap: 10px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

textarea {
  flex-grow: 1;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
}

button {
  padding: 0 24px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 12px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #888;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}
</style> 